--require "MainScene"

ZhanDouScene={}
ZhanDouSceneFunc={}
ZhanDouSceneFunc.__index = ZhanDouSceneFunc
setmetatable(ZhanDouScene, ZhanDouSceneFunc)
--ZhanDouScene.currentStronghold = -1
--ZhanDouScene.currentCheckpoint = -1

ZhanDouScene.NodeID = {CloseButton=1001}
local JuDianItemNodeID = {CheckPointNameLabel=3001, StrongholdNameLabel=3003, ImgBK=3002, StrongholdButton=3004, StrongholdDescLabel=3005, StarBK=3006}

ZhanDouSceneFunc.getNode = function(self, s, c)
  local l = {}
  setmetatable(l, ZhanDouSceneFunc)
  l.node = CCBReader:load("ZhanDouScene.ccbi")
  print("ZhanDouScene.getNode", ZhanDouScene.node)
  ZhanDouScene.instance = l
  l:init(s,c) 
  return l 
end

ZhanDouSceneFunc.getScene = function()
  local sc = CCScene:create()
  sc:addChild(ZhanDouScene:getNode().node)  
  print("ZhanDouScene.getScene", sc)
  return sc
end

ZhanDouSceneFunc.init = function(self, s, c)
  --self.currentStronghold = 0 
  --self.currentCheckpoint = 0
  setObjectExtTable(self.node:getChildByTag(1001), self)
  self:initStrongholdTable()
  if s~=nil and c~=nil then
    self.currentStronghold = s
    self.focusCheckpoint = c
  end
  --if ZhanDouScene.currentStronghold>0 and ZhanDouScene.currentCheckpoint>0 then
  --  self.currentStronghold = ZhanDouScene.currentStronghold
  --  self.currentCheckpoint = ZhanDouScene.currentCheckpoint 
  --end
  --self.checkpointTable = self:getCheckPointTable(self.currentStronghold)
  --self.node:addChild(self.checkpointTable)
  self:setStrongholdFocus(self.currentStronghold)
  self:setCheckpointFocus(self.focusCheckpoint) 
  --self:setStrongholdFocus(1)
  --self:setCheckpointFocus(3) 
  --TypeCast(self.checkPointTable,"CCScrollView"):setContentOffset(ccp(, 0))
  --self.currentCheckpoint = 3 
  --local tmp = self.currentCheckpoint-1
  --if tmp<0 then tmp=0;end 
end

ZhanDouSceneFunc.setCheckpointFocus = function(self, index)
  local checkpoints = UserData.config.models.Stronghold[self.currentStronghold].checkpoints
  local count = #checkpoints 
  if index<3 then
    return
  end
  local tx = (index-2)*300
  if tx>(count-3)*300 then tx=(count-3)*300 end 
  local offset = TypeCast(self.checkPointTable,"CCScrollView"):getContentOffset()
  TypeCast(self.checkPointTable,"CCScrollView"):setContentOffset(ccp(-tx, offset.y))
end
ZhanDouSceneFunc.setStrongholdFocus = function(self, index)
  --if index==ZhanDouScene.currentStronghold then return;end
  local item1 = self.strongholdItems:objectAtIndex(self.currentStronghold-1)
  item1=TypeCast(item1, "CCLayer")
  item1:setPosition(ccp(0,0))
  local item2 = self.strongholdItems:objectAtIndex(index-1)
  item2=TypeCast(item2, "CCLayer")
  item2:setPosition(ccp(0,10))
  self.currentStronghold = index

  if self.checkpointTable then
    self.node:removeChild(self.checkpointTable, true)
  end
  local table = self:getCheckPointTable(index)
  self.checkpointTable = table 
  self.node:addChild(self.checkpointTable)
  print("onStronghold", self.currentStronghold, index)
end

ZhanDouSceneFunc.initStrongholdTable = function(self)
  local strongholds = UserData.config.models.Stronghold
  local count = #strongholds
  if count<=0 then
    return
  end
  
  local items = CCArray:create()
  for i=1,13 do
    local item = CCBReader:load("StrongholdItem.ccbi")
    local name = strongholds[i].name 
    local lb = item:getChildByTag(JuDianItemNodeID.StrongholdNameLabel)
    TypeCast(lb, "CCLabelTTF"):setString(name)
    lb = item:getChildByTag(JuDianItemNodeID.StrongholdDescLabel)
    TypeCast(lb, "CCLabelTTF"):setString(string.format("Lv%d", strongholds[i].level))
    local b = item:getChildByTag(JuDianItemNodeID.StrongholdButton)
    setObjectExtTable(b, self)
    b:setTag(i)
    b=TypeCast(b, "CCButton")
    b:setEnabled(false)
     
    item:setContentSize(CCSizeMake(170, 120))
    items:addObject(item)
  end
  print("ZhanDouScene.initStrongholdTable basic")
  local completedStrongholds = UserData.userinfo.host.strongholds
  for i=1,#completedStrongholds do
    local id = completedStrongholds[i]
    local item = TypeCast(items:objectAtIndex(id-1), "CCNode")
    local lb = item:getChildByTag(JuDianItemNodeID.StrongholdDescLabel)
    TypeCast(lb, "CCLabelTTF"):setColor(ccc3(0,255,0))
    lb:setString("已征服")
    local b = item:getChildByTag(id)
    --print("completedStrongholds", b)
    b=TypeCast(b, "CCButton")
    b:setEnabled(true)
  end
  print("ZhanDouScene.initStrongholdTable done")

  local currentStrongholds = UserData.userinfo.host.currentStronghold
  for k,v in pairs(currentStrongholds) do
    --local item = items:objectAtIndex(k-1)
    local item = TypeCast(items:objectAtIndex(k-1), "CCNode")
    local lb = item:getChildByTag(JuDianItemNodeID.StrongholdDescLabel)
    lb = TypeCast(lb, "CCLabelTTF")
    lb:setColor(ccc3(255,255,0))
    lb:setString("进行中")
    self.currentStronghold = tonumber(k)
    local b = item:getChildByTag(k)
    b=TypeCast(b, "CCButton")
    b:setEnabled(true)
  end
  print("ZhanDouScene.initStrongholdTable doing")


  print("ZhanDouScene.initStrongholdTable items", items:count())
  local tableview = CCTableView:create(0, CCSizeMake(940, 130), items)
  tableview:setPosition(10, -10)
  self.node:addChild(tableview)
  self.strongholdItems = items
end

ZhanDouSceneFunc.setEvalStar = function(self, eval)
  print("ZhanDouScene.setEvalStar", self.currentCheckpoint, eval, self.checkpointItems:count())
  local item = self.checkpointItems:objectAtIndex(self.currentCheckpoint-1)
  item=TypeCast(item, "CCLayer")
  local starBK = item:getChildByTag(JuDianItemNodeID.StarBK)
  local starSp = CCSprite:create(string.format("evlstar%d.png", eval))
  starSp:setPosition(starBK:getPosition())
  starSp:setTag(JuDianItemNodeID.StarBK)
  item:addChild(starSp)
  item:removeChild(starBK, true)
end

ZhanDouSceneFunc.getCheckPointTable = function(self, index)
  local allCheckPoints = UserData.config.models.Checkpoint
  print("ZhanDouScene.getCheckPointTable",index,#allCheckPoints)
  local checkpoints = UserData.config.models.Stronghold[index].checkpoints
  print("ZhanDouScene.initTable", #allCheckPoints, checkpoints, #UserData.config.models.Stronghold)
  local count = #checkpoints
  if count<=0 then
    return
  end
  --if self.checkpointItems==nil then
    self.checkpointItems = CCArray:create()
  --end
  --local items = CCArray:create()
  self.checkpointButtons = {}
  local flag = true 
  for i=1,count do
    beg = usecond()
    local item = nil
    --if i-1<self.checkpointItems:count() then
    --  item = self.checkpointItems:objectAtIndex(i-1)
    --else
      item = CCBReader:load("JuDianItem.ccbi")
      self.checkpointItems:addObject(item)
    --end
    e = usecond()
    --print("ZhanDouScene.initTable load cost", e-beg)
    local s = item:getContentSize()
    item:setContentSize(CCSizeMake(300, 390))
    local s = item:getContentSize()
    local lb = item:getChildByTag(JuDianItemNodeID.CheckPointNameLabel)
    local cp = allCheckPoints[checkpoints[i]]
    TypeCast(lb, "CCLabelTTF"):setString(cp.name)
  
    beg = usecond()  
    if i<100 then
    local imgName = "checkpoint_huweidui.png"
    if string.len(cp.asset)>0 then
      local p1,p2 = string.find(string.reverse(cp.asset), "_")
      local tmp= string.sub(cp.asset, -p1+1)
      imgName = string.format("checkpoint_%s.png", tmp) 
      lb:setColor(ccc3(255,255,0))
    end
    b1 = usecond()
    local button = CCButton:createWithFileName("onCheckPoint", imgName, imgName, imgName, "") 
    e1=usecond()
    --print("ZhanDouScene.initTable button cost", e1-b1)
    setObjectExtTable(button, self)
    local imgBK = item:getChildByTag(JuDianItemNodeID.ImgBK)
    button:setPosition(imgBK:getPosition())
    button:setTag(i)
    item:removeChild(imgBK, true)
    item:addChild(button)
    print("####", #self.checkpointButtons, button)
    self.checkpointButtons[#self.checkpointButtons+1] = button
    b1=usecond()
    local starBK = item:getChildByTag(JuDianItemNodeID.StarBK)
    local eval = UserData.userinfo.host.evaluate[checkpoints[i]+1]
    --print("ZhanDouScene.initTables", checkpoints:at(i), eval, UserData.userinfo.host.evaluate)
    if eval~=nil then
      local starSp = CCSprite:create(string.format("evlstar%d.png", eval)) 
      starSp:setPosition(starBK:getPosition())
      starSp:setTag(JuDianItemNodeID.StarBK)
      item:addChild(starSp)
    elseif flag==true then
      self.focusCheckpoint = i
      local starSp = CCSprite:create("evlstar11.png") 
      starSp:setPosition(starBK:getPosition())
      starSp:setTag(JuDianItemNodeID.StarBK)
      item:addChild(starSp)
      flag=false
    else
      local maskSp = CCSprite:create("mask1.png")
      maskSp:setPosition(ccp(152, 196))
      --maskSp:setTag(JuDianItemNodeID.StarBK)
      item:addChild(maskSp)
      setTouchEnabledAll(item, false)
    end
    e1=usecond()
    --print("ZhanDouScene.initTable img cost", e1-b1)
    item:removeChild(starBK, true)
  end
    e = usecond()  
    --print("ZhanDouScene.initTable set cost", e-beg)
    --items:addObject(item)
  end
  --local tableBK = ZhanDouScene.node:getChildByTag(ZhanDouNodeID.TableBK)
  --local size = tableBK:getContentSize()
  print("ZhanDouScene.initTable items", self.checkpointItems:count())
  local tableview = CCTableView:create(0, CCSizeMake(940, 390), self.checkpointItems)
  tableview:setPosition(10, 150)
  --ZhanDouScene.node:addChild(tableview)
  --self.checkpointItems = items
  self.checkPointTable = tableview
  return tableview
end

ZhanDouSceneFunc.getCheckpointInfoID = function(self)
  local strongholds = UserData.config.models.Stronghold
  local checkpoints = UserData.config.models.Checkpoint
  return strongholds[self.currentStronghold].checkpoints[self.currentCheckpoint]
end
ZhanDouSceneFunc.getCheckpointInfo = function(self, sid, index)
  --local strongholds = UserData.config.models.Stronghold
  local checkpoints = UserData.config.models.Checkpoint
  local cid = self:getCheckpointInfoID() 
  local info = checkpoints[cid] 
  print("ZhanDouSceneFunc.getCheckpointInfo", cid, info)
  return info
end

ZhanDouSceneFunc.onStronghold = function(self, node)
  local tag = node:getTag()
  if tag==self.currentStronghold then
    return
  end
  --[[
  if self.checkpointTable then
    self.node:removeChild(self.checkpointTable, true)
  end
  local table = self:getCheckPointTable(tag)
  self.checkpointTable = table 
  self.node:addChild(self.checkpointTable)
  print("onStronghold", self.currentStronghold, tag)
  ]]
  self:setStrongholdFocus(tag)
end

ZhanDouSceneFunc.onCheckPoint = function(self, node)
  self.oldCheckpointTableOffset = TypeCast(self.checkPointTable,"CCScrollView"):getContentOffset() 
  self.currentCheckpoint = node:getTag() 
  local checkpoints = UserData.config.models.Stronghold[self.currentStronghold].checkpoints
  local nid = checkpoints[node:getTag()]
  print("onCheckPoint", node:getTag(), nid)
  
  if UserData.userinfo.host.soldiers>0 then  
    --setTouchEnabledAll(self.node, false)
    LoadScene:showLoadingScene()
    NetworkRequest.getBattlePVE(self.currentStronghold, nid, "onGetBattlePVE", self) 
  else
    showMessage("兵力不足，请补充兵力！", ccc3(255,255,0))
  end
end
ZhanDouSceneFunc.onGetBattlePVE = function(self, data)
  --data = string.sub(data, 2, -2)
  --print("onGetBattlePVE #", data, "#")
  --local path=CCFileUtils:sharedFileUtils():fullPathFromRelativePath("tmp.json")
  --  local txt=CCString:createWithContentsOfFile(path):getCString()
  --  local res = cjson.decode(txt)
  --txt = '{"fda":1}'
  print("ZhanDouSceneFunc.onGetBattlePVE", data)
  LoadScene:removeLoadingScene()
  local res = cjson.decode(data)
  if res.ret~=0 then
    showMessage(res.msg, ccc3(255,255,0))
    setTouchEnabledAll(self.node, true)
  else
    setTouchEnabledAll(self.node, false)
    NetworkRequest.syncData(res)
    local cid = self:getCheckpointInfoID()
    UserData.userinfo.host.evaluate[cid+1] = res.data.evaluate 
    local info = self:getCheckpointInfo()
    local war = WarScene:getNode(info.name, self, res)
    --self:updateTable()
    self.node:addChild(war.node)
    --self.warScene = war 
    --self:showZhanDouView(data)
    --self:showWinWnd(1,1,1)
    --showMessage("战斗失败", ccc3(255,0,0))
  end
end
ZhanDouSceneFunc.fightEnd = function(self)
  setTouchEnabledAll(self.node, true)
  self:updateTable()
  RenWuGuide.nextStep()
end

ZhanDouSceneFunc.updateTable = function(self)
  if self.checkpointTable then
    self.node:removeChild(self.checkpointTable, true)
  end 
  self.checkpointTable = self:getCheckPointTable(self.currentStronghold)
  self.node:addChild(self.checkpointTable)
  TypeCast(self.checkPointTable,"CCScrollView"):setContentOffset(self.oldCheckpointTableOffset)
end

ZhanDouSceneFunc.onCloseZhanDouScene = function(self, node, event)
  print("onCloseZhanDouScene")
  MainScene.scene:removeChild(node:getParent(), true)
  setTouchEnabledAll(MainScene.node, true)
  MainScene.setState()
  ZhanDouScene.instance = nil
  ZhanDouScene.currentStronghold = 0--self.currentStronghold
  ZhanDouScene.currentCheckpoint = 0--self.currentCheckpoint 
  RenWuGuide.nextStep()
end
